package com.serkol.driving.learning.handler;

import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@MapperScan("com.serkol.driving.learning.mapper")
//@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig implements InitializingBean {

/*    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }*/

    @Bean
    public MyMetaObjectHandler myLogicSqlInjector() {
        return new MyMetaObjectHandler();
    }




    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        // 取消MyBatis Plus的最大分页500条的限制
        paginationInnerInterceptor.setMaxLimit(100000L);
        MyDynamicTableNameInterceptor myDynamicTableNameInterceptor = new MyDynamicTableNameInterceptor();
        HashMap<String, MyTableNameHandler> map = new HashMap<String, MyTableNameHandler>(2) {{
            System.out.println("----------------------------------------------------");


            //整个函数返回的结果就是替换后的新表名，这个生成的表名的规则可以自己随便指定
            put("question_bank", (sql, tableName, student) -> getTableName(sql, tableName, student));



        }};
        myDynamicTableNameInterceptor.setTableNameHandlerMap(map);
        interceptor.addInnerInterceptor(myDynamicTableNameInterceptor);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);

        return interceptor;


    }

    private String getTableName(String sql, String tableName, Object student) {
        System.out.println("Index  sssssssssssssssssssssssssssssssss");
        System.out.println("-----------------SQL1------------------------------" + sql);
        System.out.println("getTableName:" + tableName);
        if (sql.indexOf("SELECT") > -1) {
            return tableName + " as x";

        } else {
            return tableName;
        }
    }


    @Bean
    public GlobalConfig globalConfig() {
        GlobalConfig config = new GlobalConfig();
        // 开启自动填充功能
        config.setMetaObjectHandler(new MyMetaObjectHandler());
        return config;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }
}
